package com.example.lib;

public class MyClass {
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 4, 7, 11, 15},
                {2, 5, 8, 12, 19},
                {3, 6, 9, 16, 22},
                {10, 13, 14, 17, 24},
                {18, 21, 23, 26, 30},
        };
        System.out.println(findNumberIn2DArray(matrix,5));
    }
    public static boolean findNumberIn2DArray(int[][] matrix, int target) {
        int m = matrix[0].length-1;
        int n = matrix.length-1;
        int currentN = 0;
        int currentM = 0;
        if (target > matrix[n][m]){
            return false;
        }
        while(m != 0 || n != 0){
            if (matrix[n][m] == target){
                return true;
            }
            if(target < matrix[n][m]){
                n--;
                m--;
            }else {
                for (int t =0;t<matrix[0].length-1;t++){
                    currentN = n+1;
                    if(currentN == matrix.length || target <matrix[currentN][t]){
                        break;
                    }
                    if(target == matrix[currentN][t]){
                        return true;
                    }
                }
                for (int t =0;t<matrix.length-1;t++){
                    currentM = m+1;
                    if(currentM == matrix[0].length || target < matrix[t][currentM]){
                        break;
                    }
                    if(target == matrix[t][currentM]){
                        return true;
                    }
                }
                return false;
            }
        }
        return false;
    }











}